<?php

namespace app\common\model\xiluhouse;

use think\Model;
use traits\model\SoftDelete;
use think\Cache;

class Area extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'xiluhouse_area';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'level_text',
        'is_re_text',
        'status_text'
    ];



    public function getLevelList()
    {
        return ['1' => __('Level 1'), '2' => __('Level 2'), '3' => __('Level 3'), '4' => __('Level 4')];
    }

    public function getIsReList()
    {
        return ['1' => __('Is_re 1'), '2' => __('Is_re 2')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Status normal'), 'hidden' => __('Status hidden')];
    }

    public function getLevelTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['level']) ? $data['level'] : '');
        $list = $this->getLevelList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsReTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_re']) ? $data['is_re'] : '');
        $list = $this->getIsReList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    /**
     * 获取所有城市
     */
    public function getCityList()
    {
        $data = $this->cache('city', 6000)->where('level', 2)->where('status', 'normal')->order(['pinyin' => 'asc'])->select();
        return $data;
    }
    /**
     * 根据城市获取其下区县、街道
     */
    public function getRegionStreet($city, $type = 1)
    {
        $city_id = $this->where('level', 2)->where('status', 'normal')->where('name', 'like', $city . '%')->value('id') ?: 0;
        if (!$city_id) {
            return [];
        }
        // 获取区县
        $areaList = $this->where('level', 3)->where('status', 'normal')->where('pid', $city_id)->select();
        if ($type == 1) {
            foreach ($areaList as $key => $value) {
                $areaList[$key]['list'] = $this->where('level', 4)->where('pid', $value['id'])->select();
            }
        }

        return $areaList;
    }

    /**
     * 根据经纬度获取城市
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area
     */
    public function getCityFromLngLat($lng, $lat)
    {
        $arr = getAddr($lat, $lng);
        if (isset($arr['city'])) {
            $city = $this->where('level', 2)->where('status', 'normal')->where('name', 'like', $arr['city'] . '%')->value('name') ?: '';
            return $city;
        } else {
            return '';
        }
    }
}
